package pb

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

func UpdatePfUser(user map[string]interface{}, uid int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	condition := fmt.Sprintf(`uid = %v`, uid)
	values, sql := UpdateSql(TablePfUser, user, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

type UnofficialPfUser struct {
	Uid        int64  `json:"uid"`
	Nickname   string `json:"nickname"`
	Phone      string `json:"phone"`
	Status     int64  `json:"status"`
	HeadImgUrl string `json:"head_img_url"`
	CreateTime int64  `json:"create_time"`
}

//列出所有一级未审核的代理(包换:输入授权码成功,绑定手机成功,审核通过但未激活的)
func ListAllExpirePfUser() ([]UnofficialPfUser, error) {
	where := fmt.Sprintf(" status IN (%v,%v) AND level = %v",
		BindPhoneSuccess, VerifyPass, Level1)
	sql := fmt.Sprintf(`
		SELECT
			uid,nickname,phone,status,create_time
		FROM
			%v
		WHERE
			%v
		`, TablePfUser, where)
	o := NewDBOrm(DBChessPartner)
	var user []UnofficialPfUser
	_, err := o.Raw(sql).QueryRows(&user)
	if CheckNoExist(err) {
		return user, nil
	}
	return user, err
}

//列出未审核的一级代理
func ListUnofficialPfUser(p ListParams, phone string, uid int64, multiOrm ...orm.Ormer) ([]UnofficialPfUser, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(" status IN (%v,%v) AND level = %v",
		BindPhoneSuccess, VerifyPass, Level1) //非正式一级代理
	if uid != 0 {
		where = where + fmt.Sprintf(" AND uid = %v", uid)
	}
	if phone != "" {
		where = where + fmt.Sprintf(" AND phone = %v", phone)
	}
	sql := fmt.Sprintf(`
		SELECT
			uid,nickname,phone,status,head_img_url,create_time
		FROM
			%v
		WHERE
			%v
		ORDER BY
			create_time DESC
		LIMIT ?,?
		`, TablePfUser, where)
	o := NewOrm(multiOrm, DBChessPartner)
	var user []UnofficialPfUser
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&user)
	if CheckError(err) {
		return user, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`, TablePfUser, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return user, count, err
	}
	return user, count, nil
}
